"""
批量获取指定源文件夹中所有.mp4视频的比特率，并按照码率从小到大排序后输出。
"""
import subprocess
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor


def get_bitrate(video_path):
    cmd = f'ffprobe -v error -select_streams v:0 -show_entries stream=bit_rate -of default=noprint_wrappers=1:nokey=1 "{video_path}"'
    try:
        # print(f"正在获取视频{video_path.name}比特率...")
        bitrate_process = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
        bitrate_output = bitrate_process.stdout.decode().strip()
        bitrate_bps = int(bitrate_output)
        bitrate_mbps = bitrate_bps / 1000000  # 转换为Mbps
        return video_path, bitrate_mbps
    except ValueError:
        print(f"无法获取{video_path}的比特率")
        return None


# 源文件夹路径
source_folder = Path(r"E:\手机备份\DCIM\Camera\短视频")

# 获取源文件夹中的所有.mp4文件路径列表
video_paths = list(source_folder.glob("*.mp4"))

# 使用多线程获取视频比特率
with ThreadPoolExecutor(max_workers=8) as executor:
    video_bitrates = {result[0]: result[1] for result in executor.map(get_bitrate, video_paths) if result is not None}

# 按照码率从小到大排序
sorted_videos = sorted(video_bitrates.items(), key=lambda x: x[1], reverse=False)

# 格式化输出
for video_path, bitrate in sorted_videos:
    print(f"{video_path.name}: {bitrate:.2f} Mbps")
